package com.zsrt.oa.user.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zsrt.oa.user.service.UserService;
import com.zsrt.oa.user.service.impl.UserServiceImpl;
import com.zsrt.utils.DBUtils;

/**
 * 这是用户的控制层
 * @author 罗智壕-13424431416
 *
 * 2017年6月8日
 */
public class UserController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	/**
	 * 初始化用户的服务层
	 */
	private UserService service = new UserServiceImpl();
	
	/**
	 * 重写HttpServlet中的service方法
	 */
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String method = request.getParameter("method");
		
		
		if(null != method && !"".equals(method.trim())){
			HttpSession session = request.getSession();
			//初始化一个集合，到时候返回给前台
			Map<String, Object> map = new HashMap<String,Object>();
			
			if("registerGudge".equals(method)){
				String userPhone = request.getParameter("userPhone");
				
				//调用注册判断手机号码是否存在
				service.registerGudge(userPhone, map);
			}else if("register".equals(method)){
				String userName = request.getParameter("userName");
				String userPassword = request.getParameter("userPassword");
				String userPhone = request.getParameter("userPhone");
				
				//调用用户注册方法
				service.userAdd(userName, userPassword, userPhone, map);
			}else if("login".equals(method)){
				String userPassword = request.getParameter("userPassword");
				String userPhone = request.getParameter("userPhone");
				session.setAttribute("currentUser", userPhone);
				//调用用户登录方法
				service.userLogin(userPassword, userPhone, map);
				Object str = map.get("result");
				if(str.equals("success")){
					request.getSession();
					request.getServletContext().setAttribute("currentPhone", userPassword);
				}
				
			}else if("currentUser".equals(method)){
				
				//查询当前用户
				map.put("currentUser", session.getAttribute("currentUser"));
			}else if("myMessage".equals(method)){
				
				//查询当前用户的信息
				service.myMessage(session.getAttribute("currentUser"), map);
			}else if("counter".equals(method)){
				Object counter = request.getServletContext().getAttribute("counter");
				map.put("counter", counter);
			}else if("destroy".equals(method)){
				session.invalidate();
			}
			
			
			//返回json格式到前台
			DBUtils.toJson(map, response);
		}
		
	}
}
